import autoDisposeWhenUnload from "./autoDisposeWhenUnload";

const instanceList = [];
const privateDataList = [];

autoDisposeWhenUnload(function () {
    instanceList.forEach(instance => instance?.destroy());
    instanceList.splice(0, instanceList.length);
    privateDataList.splice(0, privateDataList.length);
});

export default class AwesomeCache {
    constructor(config) {
        instanceList.push(this);
        privateDataList.push({
            expire: 1000 * config.expireSeconds,
            getContent: config.getCacheContent,
            clearCtx: null,
            content: null,
        });
    }

    refresh() {
        const data = privateDataList[instanceList.indexOf(this)];
        if (null !== data.clearCtx) {
            clearTimeout(data.clearCtx);
        }
        data.clearCtx = setTimeout(() => {
            data.content = null;
            data.clearCtx = null;
        }, data.expire);
    }

    get(forceUpdate = false) {
        const data = privateDataList[instanceList.indexOf(this)];
        if (!data.content || forceUpdate) {
            const content = data.getContent();
            if (content instanceof Promise) {
                return content.then(res => {
                    this.refresh();
                    data.content = res;
                    return res;
                });
            } else {
                data.content = content;
            }
        }
        this.refresh();
        return data.content;
    }

    destroy() {
        const data = privateDataList[instanceList.indexOf(this)];
        if (!data.destroyed) {
            data.destroyed = true;
            data.content = null;
            data.clearCtx = null;
            data.expire = null;
            data.getContent = null;

            const index = privateDataList.indexOf(data);
            instanceList[index] = null;
            privateDataList[index] = null;
        }
    }
}
